package com.cyx.order.service;

import com.cyx.order.mapper.OrderMapper;
import com.cyx.order.model.OrderInfo;
import com.cyx.order.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderService.class);
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    // 计数器
    private AtomicInteger count = new AtomicInteger(1);

    private List<ServiceInstance> instances;

    @PostConstruct
    public void init() {
        // 从eureka中获取服务列表
        instances = discoveryClient.getInstances("product-service");
    }

//    public OrderInfo getOrderInfo(Long id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//        // 获取服务提供者的uri
//        String url = "http://localhost:9090/product"+orderInfo.getProductId();
//        log.info("远程调用url：{}", url);
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }

//    public OrderInfo getOrderInfo(Long id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//
//        // 获取服务提供者的uri
//        int index = count.getAndIncrement() % instances.size();
//        String uri = instances.get(index).getUri().toString();
//
//        String url = uri + "/product/" + orderInfo.getProductId();
//        log.info("远程调用url：{}", url);
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }

    // 自定义负载均衡
    public OrderInfo getOrderInfo(Long id) {
        OrderInfo orderInfo = orderMapper.selectOrderById(id);

        // 获取服务提供者的url
        String url = "http://product-service/product/" + orderInfo.getProductId();
        log.info("远程调用url：{}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}
